package com.tenbent.product.base.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

/**
 * 定义httpBasic 启动 接口基于基本身份验证失败，返回错误信息类
 *
 * 说明: 基本身份认证是系统与系统，接口与接口间掉用身份验证的方式，
 *
 * 如果验证失败，不应返回登录页面，应该告诉调用方401认证失败信息。
 *
 * 对于调用方需要在http heads 中添加 Authorization=Base64(user:password)
 *
 * 字符串 。例如 headers.add("Authorization", "Basic " + base64ClientCredentials);
 *
 * 怎么生成 base64ClientCredentials 呢 ，例如
 *
 * String plainClientCredentials="myusername:mypassword";
 *
 * String base64ClientCredentials = new
 * String(Base64.encodeBase64(plainClientCredentials.getBytes()));
 *
 * HttpHeaders headers = getHeaders();
 *
 * headers.add("Authorization", "Basic " + base64ClientCredentials);
 *
 * @author Randy
 *
 *         Created by ThinkPad on 2017/6/19.
 */
public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

	private Logger log = LoggerFactory.getLogger(CustomBasicAuthenticationEntryPoint.class);

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {

		log.debug("401 Authentication is Failure,reason : {}", authException.getMessage());
		// 认证失败，发送错误信息
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");
		PrintWriter writer = response.getWriter();
		writer.println("HTTP Status 401 : " + authException.getMessage());
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		setRealmName("MY_TEN_BENT_REALM");
		super.afterPropertiesSet();
	}
}
